<?php

namespace App\Jobs;

use App\Models\Cookbook;
use GifCreator\GifCreator;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Storage;

class VideoShortUrl implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $timeout = 60;

    public $tries = 2;

    private $cookbook_id;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($cookbook_id)
    {
        $this->queue = 'video_short_url';
        $this->cookbook_id = $cookbook_id;
    }


    public function handle()
    {
        \Log::info("==============start video short url job =========================");
        $model = Cookbook::find($this->cookbook_id);
        $frames = [];
        $k = 1;
        for ($i = 0;$i<=8;$i++) {
            $k = $k + 0.7;
            $url = $model->video_url . '?vframe/jpg/w/350/offset/' . $k;
            array_push($frames, $url);
        }
        $durations = array();
        for ($i = 0; $i <= 10; $i++) {
            array_push($durations, 50);
        }
        // Initialize and create the GIF !
        $gc = new GifCreator();
        $gc->create($frames, $durations, 0);
        $gifBinary = $gc->getGif();
        $disk = Storage::disk('qiniu');
        $file_name = generateRandomString(60) . ".gif";
        $disk->put($file_name, $gifBinary);
        $old_short_url = $model->short_video_url;
        $url = env('QINIU_URL') . "/" . $file_name;
        $model->short_video_url = $url;
        $model->save();
        if ($old_short_url) {
            $old_short_url= ltrim($old_short_url, env('QINIU_URL'));
            $disk->delete($old_short_url);
        }
        \Log::info("==============end video short url  job ============================");
    }
}
